import React, { Component } from 'react';
import { Button, Tooltip, Spin, Modal } from 'antd';

import { WeaInputSearch, WeaAlertPage, WeaErrorPage, WeaLocaleProvider, WeaDateSwitch } from 'ecCom';
import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;

import Apis from '../../apis/car';
import moment from 'moment';
import { inject, observer } from 'mobx-react';
import CarViewDialog from '../car/dialog/CarViewDialog';

const getLabel = WeaLocaleProvider.getLabel;
let carCondition = {
  carNo: '',
  currentdate: '',
  bywhat: '',
  subId: '',
  subName: '',
  carId: '',
  ismobile: '',
};
const carFlowData = {};
import '../../lib/wdCalendar_lang_wev8';

const i18n = window.meetingCalendarI18n;
@inject('carUseContainerStore')
@observer
class CarUseContainerMobile extends Component {
  constructor(props) {
    super(props);
    carCondition = {
      carNo: '',
      currentdate: '',
      bywhat: '',
      subId: '',
      subName: '',
      carId: '',
    };
    this.searchByCarNo = this.searchByCarNo.bind(this);
    this.query = this.query.bind(this);
    this.state = {
      timeType: 'day',
      date: new Date(),
      subId: props.subId,
      subName: props.subName,
      color: {},
      baseLoading: true,
      cars: [],
      carUseTabs: [], // carUseTabs中的车辆和carUseID中车辆id一一对应
      carUseID: [],
      useMap: {}, // key为carid，value为使用信息
      startHour: 0,
      endHour: 23,
      duration: 0,
      carNo: '', // 搜索栏
      carLoading: true,
      pageTabKey: '',
      carId: '',
      createObj: {},
      createVisible: false,
      previewMeetingId: '',
      roomPlanVisible: false,
      conHeight: 0,
      tabHeight: 0,
      listHeight: 0,
      dialogZIndex: 801,
      callback: undefined,
      scrollType: '',
    };
  }

  componentDidMount() {
    Apis.getCarReportBaseData().then((result) => {
      let { agreementColor, conflictedColor, usedColor, subname, timestart, timeend, roomConflictType } = result;
      agreementColor || (agreementColor = '#FFE4C4'), conflictedColor || (conflictedColor = '#FBDFEB'), usedColor || (usedColor = '#E3F6D8');
      this.setState({
        subName: subname,
        color: { agreementColor, conflictedColor, usedColor },
        baseLoading: false,
        startHour: timestart,
        endHour: timeend,
        roomConflictType,
      });
    });


    const { carUseContainerStore } = this.props;
    this.query();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.subId != this.props.subId) {
      carCondition.subId = nextProps.subId;
      carCondition.subName = nextProps.subName;
      this.setState({
        subId: nextProps.subId,
        subName: nextProps.subName,
      }, this.query);
    }
    if (this.state.dialogZIndex != nextProps.dialogZIndex && nextProps.dialogZIndex) {
      this.setState({
        dialogZIndex: nextProps.dialogZIndex,
      });
    }
  }

  componentDidUpdate(prevProps, prevState) {
    // 处理高度自适应问题
    let container = jQuery('.car-container', ReactDOM.findDOMNode(this)),
      conHeight = this.props.height ? (this.props.height - 108) : container.height();
    let tab = jQuery('.car-tab', container),
      tabHeight = tab.height();
    if (tabHeight <= 0) {
      tabHeight = this.state.tabHeight;
    }
    let listHeight;
    if (tabHeight > (conHeight * 0.55)) {
      listHeight = (conHeight * 0.45);
      tabHeight = (conHeight * 0.55);
    } else {
      listHeight = conHeight - tabHeight;
    }
    if (conHeight !== this.state.conHeight || tabHeight !== this.state.tabHeight || listHeight !== this.state.listHeight) {
      this.setState({
        conHeight,
        tabHeight,
        listHeight,
      });
    }
  }

    /* 日组件切换回调 */
    onChangeWeaDateSwitch = (type, date, range) => {
      const dateClone = moment(date);// 克隆date
      const stateDate = moment.isMoment(this.state.date) ? this.state.date : moment(this.state.date);
      if (dateClone.format('YYYY-MM-DD') != stateDate.format('YYYY-MM-DD')) { // 日期切换
        const currentdate = dateClone.format('YYYY-MM-DD');
        carCondition.currentdate = currentdate;
        carCondition.carId = '';
        this.setState({ date: dateClone.toDate(), carId: '' }, this.query);
      }
    }

    searchByCarNo(value = this.state.carNo) {
      carCondition.carId = '';
      this.setState({
        carId: '',
        carNo: value,
      }, this.query(value));
    }

    /* 查询车辆使用情况与车辆列表 */
    query(value = this.state.carNo) {
      const clearUserMap = true;
      const { timeType } = this.state;
      const newState = {
        carNo: value,
      };
      this.setState(newState);
      carCondition.carNo = value;
      const params = this.getQueryParams(value);
      clearUserMap && (newState.useMap = {});
      Apis.getCarReportData(params).then(
        (res) => {
          const duration = (timeType == 'day' && res.dspUnit > 0) ? 60 / res.dspUnit : 0;
          const useMap = {};
          const arrCar = [];
          const arrID = [];
          const carss = [];
          const dspUnit = res && res.dspUnit ? res.dspUnit : 0;
          // 车辆
          res && res.cars && res.cars.map((key) => {
            const objCar = {};
            const objID = {};
            objCar.title = key.name;
            objCar.key = key.id;
            objID.id = key.id;
            arrCar.push(objCar);
            arrID.push(objID);
            carss[key.id] = key;
            return 0;
          });
          // 获取车辆使用信息
          res.datas && res.datas.forEach((obj) => {
            if (!obj.carid) return;
            useMap[obj.carid] = obj.info;
          });
          this.setState({
            cars: res.cars || [],
            useMap,
            duration,
            carUseTabs: arrCar, // roomTabs中的会议和roomid中会议id一一对应
            carUseID: arrID,
            dspUnit,
            carss,
            carLoading: false,
          });
        },
      );
    }

    /* 根据state与传入的车辆名称生成查询用的参数，既可以给车辆使用情况用，也可以给车辆列表用 */
    getQueryParams(value = this.state.carNo) {
      return carCondition;
    }

    render() {
      // 上方使用的基础数据
      const { timeType, baseLoading, color, date } = this.state;
      if (baseLoading) {
        return (
          <div className="align-center top40"><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@ux85ii`} /></div>
        );
      }
      // 列表中使用的数据
      const { carLoading, startHour, endHour, cars } = this.state;

      const { blockNum, tableTitle } = this.getTableHeaderInfo(timeType, date, startHour, endHour);

      // 高度控制
      // if (tabHeight + listHeight <= (conHeight)) {
      //     tabHeightValue = "auto";
      //     listHeightValue = "auto";
      // } else if (tabHeight >= (conHeight) * 0.55 && listHeight >= (conHeight) * 0.45) {
      //     tabHeightValue = "55%";
      //     listHeightValue = "45%";
      // } else if (tabHeight > (conHeight) * 0.55 && listHeight <= (conHeight) * 0.45) {
      //     tabHeightValue = (conHeight) - listHeight;
      //     listHeightValue = "auto";
      // } else {
      //     tabHeightValue = "auto";
      //     listHeightValue = (conHeight) - tabHeight;
      // }
      return (
        <div className="wea-car-con f12">

          <div className="car-top">
            <div className="car-top-con line" style={{ paddingLeft: 0 }}>
              <WeaDateSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaDateSwitch@8d3i4s`} onChange={this.onChangeWeaDateSwitch} typeList={[]} currentDay={date} />
              <div className="legend" style={{ marginRight: 10 }}>
                <div><div className="square" style={{ backgroundColor: color.usedColor, margin: '0 5px' }} /><span>{getLabel(19097, '占用')}</span></div>
                <div><div className="square" style={{ backgroundColor: color.conflictedColor, margin: '0 5px' }} /><span>{getLabel(386006, '冲突')}</span></div>
              </div>
            </div>
            {/* 车辆使用情况的头部 */}
            <table className="car-tab-header">
              <tbody>
                <tr className="no-border-top">
                  <th className="first align-center" style={{ width: 103 }}>{getLabel(920, '车辆')}</th>
                  <th colSpan={blockNum}>{tableTitle || `${getLabel(383375, '读取中')}...`}</th>
                </tr>
              </tbody>
            </table>
          </div>
          <div className="car-container-mobile">
            <div
              className="roomplan-table"
              ref="roomplanTable"
              key="roomplanTable"
              onTouchStart={(e) => {
                this.tableScroll(e);
              }}
            >
              <div className="roomplan-table-top" ref="roomplanTableTop">
                <div className="roomplan-table-top-head">
                  <WeaInputSearch
                    ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@i0r269`}
                    placeholder={getLabel(82291, '搜索车辆')}
                    onSearch={this.searchByCarNo}
                    value={this.state.carNo}
                  />
                </div>
                <div className="roomplan-table-top-content" ref="topTime" onScroll={this.onTopScroll} >
                  <div className="table-box">{this.getTimeItem()}</div>
                </div>
              </div>
              {carLoading && <div className="align-center top40"><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@fa5dxr`} /></div>}
              {!carLoading && (!cars || cars.length == 0) && (
                <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@op331x`} icon="icon-coms-Journal">
                  <div>暂无车辆</div>
                </WeaAlertPage>
              )}
              <div className="roomplan-table-box" ref="roomplanTableBox">
                {this.getRoomItem()}
              </div>
            </div>
          </div>
          <CarViewDialog ecId={`${this && this.props && this.props.ecId || ''}_CarViewDialog@6zv9jv`} ref="carview" />
        </div>
      );
    }
    doCancel(id, tablename, cancelname) {
      const { carUseContainerStore } = this.props;
      const parm = { id, tablename, cancelname };
      carUseContainerStore.doCancel(parm, () => this.setState({ carLoading: true }, this.query));
    }

      getTimeItem = () => {
        const { startHour, endHour } = this.state;
        const fields = [];
        for (let i = startHour; i <= endHour; i++) {
          fields.push( // 时间段格
            <div className="item" key={i}>{i}</div>,
          );
        }
        return fields;
      }

      getRoomItem = () => {
        const { startHour, endHour, cars, carId, mask, carLoading } = this.state;
        const dif = endHour - startHour + 1;
        const fields = [];
        const field = [];
        let tdList = [];
        const HH = this.refs.roomplanTableBox ? this.refs.roomplanTableBox.offsetHeight : '';
        const tableContent = (
          <table className="car-tab" style={{ width: dif * 30.1 }}>
            <tbody>
              {!carLoading && (cars && cars.length > 0) &&
                        cars.map((car, index) => {
                          tdList = this.createTdList(car, 0, index);
                          return (
                            <tr className={index == 0 ? 'no-border-top' : ''}>
                              {tdList}
                            </tr>
                          );
                        })
              }
            </tbody>
          </table>
        );

        cars && cars.map((car, index) => {
          const title = createRoomTitle(car.title);
          tdList = this.createTdList(car, 0, index);
          field.push(
            <Tooltip
              ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@7vniz9@${index}`}
              title={title}
              getTooltipContainer={() => container}
              overlayClassName="white-tooltip"
              placement="right"
            >
              <div className="head-item" key={index} >{car.name}</div>
            </Tooltip>,
          );
        });
        fields.push(
          <div className="roomplan-table-box-head" ref="roomplanTableBoxHead" key="roomplanTableBoxHead" onScroll={this.onHeadScroll} style={{ height: HH }}>{field}</div>,
          <div
            className="roomplan-table-box-content"
            key="table"
            ref="roomplanTableBoxContent"
            style={{ height: HH, overflow: mask ? 'hidden' : 'auto' }}
            onScroll={this.onscroll}
          >{tableContent}</div>,
        );
        return fields;
      }

    tableScroll = (e) => { // 解决事件相互冲突
      if (e.target.className === 'car-td-modal') {
        this.setState({ scrollType: 'table' });
      } else if (e.target.parentNode.parentNode.parentNode.className === 'car-tab' || e.target.parentNode.parentNode.className === 'car-tab') {
        this.setState({ scrollType: 'table' });
      } else if (e.target.parentNode.parentNode.className === 'car-subTable' || e.target.parentNode.className === 'car-subTable' || e.target.className === 'car-subTable') {
        this.setState({ scrollType: 'table' });
      } else if (e.target.parentNode.parentNode.className === 'roomplan-table-top-content') {
        this.setState({ scrollType: 'top' });
      } else if (e.target.className === 'car-tab') {
        if (e.target.parentNode.className === 'roomplan-table-box-content') {
          this.setState({ scrollType: 'table' });
        }
        if (e.target.parentNode.className === 'roomplan-table-top-content') {
          this.setState({ scrollType: 'top' });
        }
      } else if (e.target.className === 'head-item') {
        this.setState({ scrollType: 'head' });
      }
    }

      onTopScroll = (e) => {
        const table = this.refs.roomplanTableBoxContent;
        const topTime = this.refs.topTime;

        if (this.state.scrollType === 'top') {
          table.scrollLeft = topTime.scrollLeft;
        }
      }

      onHeadScroll = (e) => {
        const table = this.refs.roomplanTableBoxContent;
        const roomplanTableBoxHead = this.refs.roomplanTableBoxHead;

        if (this.state.scrollType === 'head') {
          table.scrollTop = roomplanTableBoxHead.scrollTop;
        }
      }

      onscroll = (e) => {
        const roomplanTableBoxHead = this.refs.roomplanTableBoxHead;
        const topTime = this.refs.topTime;
        const table = this.refs.roomplanTableBoxContent;
        if (this.state.scrollType === 'table') {
          topTime.scrollLeft = table.scrollLeft;
          roomplanTableBoxHead.scrollTop = table.scrollTop;
        }
      }

    carview = (id) => {
      this.refs.carview.wrappedInstance.open(id);
    }

    /* 获得车辆使用情况的头部 */
    getTableHeaderInfo = (timeType, date, startHour, endHour) => {
      let blockNum = 0,
        tableTitle = '',
        tableHeaders = [];
      const curmoment = moment.isMoment(date) ? date : moment(date);
      if (timeType == 'day') {
        blockNum = endHour - startHour + 1;
        tableTitle = `${curmoment.format(i18n.moment.dateformat.Md3)} ${getLabel(33425, '单位')}:${getLabel(383376, '时')}`;
        for (startHour; startHour <= endHour; startHour++) { tableHeaders.push(startHour); }
      }
      return { blockNum, tableTitle, tableHeaders };
    }

    /* 创建车辆使用情况的每一行td */
    createTdList = (room, blockNum, rowNum) => {
      const { timeType, duration, useMap } = this.state;
      // let tooltipContainer = ReactDOM.findDOMNode(this);
      const tdList = [];
      const useArray = useMap[room.id];
      // 创建冲突的、带有提示的单元格
      const createTooltipTd = function (obj, otherProps) {
        const { content, bgcolor, fontcolor, title } = obj;
        const style = { backgroundColor: bgcolor, color: fontcolor || '#000', textAlign: 'center' };
        const td = (
          <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@9k2n6s`} title={createTitle(title)} placement="bottomRight" >
            <td className="car-td" style={style} conflict {...otherProps}><div className="car-td-modal" />{content > 1 && content}</td>
          </Tooltip>
        );
        return td;
      };
      return this.createTdListInDay(duration, useArray, room, createTooltipTd, rowNum, tdList);
    }

    /* 创建时间类型为天时的单元格 */
    createTdListInDay(duration, useArray, room, createTooltipTd, rowNum, tdList) {
      let { startHour, endHour } = this.state;
      const useBlockMap = {};// 已被使用的块，数据结构：小时数:{变色的序号：{背景颜色，字体颜色，内容}，...}
      const subNum = duration == 0 ? 1 : Math.floor(60 / duration);// 每小时会被分成几段

      // 生成已被占用的时间段
      useArray && useArray.forEach((obj) => {
        // 时间处理，确认序号
        if (!obj.time) return;
        const time = obj.time.split(':');
        if (time.length != 2) return;
        let hour = parseInt(time[0]),
          minute = parseInt(time[1]);
        const idx = duration > 0 ? Math.floor(minute / duration) : 0;
        // 找到该数据对应的存储位置。
        if (!useBlockMap[hour]) useBlockMap[hour] = {};
        const useHour = useBlockMap[hour];
        useHour[idx] = obj;
      });

      /* 创建每小时内的分隔块、即第二层td的方法 */
      const createSubTd = (hour, idx, rowNum, colNum) => {
        let startMinute = idx * duration,
          endMinute = startMinute + duration - 1;
        let startTime = `${hour > 9 ? hour : `0${hour}`}:${startMinute > 9 ? startMinute : `0${startMinute}`}`,
          endTime = `${hour > 9 ? hour : `0${hour}`}:${endMinute > 9 ? endMinute : `0${endMinute}`}`;
        // 有值则说明已被占用
        if (useBlockMap[hour] && useBlockMap[hour][idx]) {
          return createTooltipTd(useBlockMap[hour][idx], {
            itemPosition: [rowNum, colNum],
            startTime,
            endTime,
            room,
          });
        }
        // 空时段
        return (
          <td className="car-td" itemPosition={[rowNum, colNum]} {...{ startTime, endTime, room }}><div className="car-td-modal" /></td>
        );
      };

        // 生成第一层td列表
      let colNum = 0;
      for (startHour; startHour <= endHour; startHour++) {
        const subTdList = [];
        for (let i = 0; i < subNum; i++) {
          subTdList.push(createSubTd(startHour, i, rowNum, colNum));
          colNum++;
        }
        const td = (
          <td>
            <table className="car-subTable">
              <tr>{subTdList}</tr>
            </table>
          </td>
        );
        tdList.push(td);
      }

      return tdList;
    }

    changeSubcompany = (nodeObj, callback) => {
      let id = '';
      let name = '';
      if (nodeObj && nodeObj.id && nodeObj.id >= 0) {
        id = nodeObj.id;
        name = nodeObj.name;
      }
      const { carUseContainerStore } = this.props;
      carUseContainerStore.clearFormFields();
      carCondition.subId = id;
      carCondition.subName = name;
      carCondition.bywhat = 4;
      carCondition.carNo = '';
      // let date = new Date();
      // let curmoment = moment.isMoment(date) ? date : moment(date);
      // let currentdate=  curmoment.format("YYYY-MM-DD");
      // carCondition.currentdate = currentdate;
      this.setState({
        subId: id,
        subName: name,
        timeType: 'day',
        // date: new Date(),
        carNo: '',
        callback,
      }, this.query);
    }
}

/* 创建车辆的提示信息，以及其它提示说明 */
const createRoomTitle = function (titleList) {
  let tipArr = [];
  if (Array.isArray(titleList) && titleList.length > 0) {
    tipArr = tipArr.concat(titleList.map(tip => <div>{tip}</div>));
  }
  return <div style={{ width: 210 }}>{tipArr}</div>;
};

/* 创建车辆的提示信息 */
const createTitle = function (titleList) {
  if (Array.isArray(titleList) && titleList.length > 0) {
    return (
      <div className="wea-roomplan-titletip">
        {titleList.map((meet, idx) => (
          <div>
            {meet.map(tip => <div>{tip}</div>)}
            {idx + 1 < titleList.length && <div className="line" />}
          </div>
        ))}
      </div>
    );
  }
  return undefined;
};

CarUseContainerMobile.defaultProps = {
  canCreate: true,
};
CarUseContainerMobile.propTypes = {
  subId: React.PropTypes.string, // 分部id
  subName: React.PropTypes.string, // 分部名称
  canCreate: React.PropTypes.bool, // 是否可在周期为天时新建
};

// 组件检错机制
class MyErrorHandler extends Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== '';
    return (
      <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@j35k4d`} msg={hasErrorMsg ? this.props.error : '对不起，该页面异常，请联系管理员！'} />
    );
  }
}

export default CarUseContainerMobile;

